import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getStorage, setStorage } from '@/stores/storage'
import { v4 as uuidv4 } from 'uuid'

export const useHomeStore = defineStore('home', () => {
  // ==================== 状态重构 ====================
  const motto = ref('今日事今日毕')
  const selectedDate = ref(new Date().toISOString().split('T')[0])
  const calendarBgImage = ref(null) // 新增：背景图状态

  // 新数据结构：基于ID的全局存储 + 日期索引
  const diaries = ref({})
  const dateIndex = ref({})
  const markedDates = ref([])

  // ==================== 工具方法 ====================
  const generateId = () => `${Date.now()}_${uuidv4().split('-')[0]}`

  const processImagePath = (img) => {
    // 处理真机与打包环境的路径差异
    return img.startsWith('file://') ? img.replace('file://', '_www/') : img
  }

  // ==================== 数据初始化 ====================
  const initFromStorage = async () => {
    try {
      const stored = await getStorage('homeStore')
      if (stored) {
        // 数据版本迁移
        if (stored._version === 1) {
          // 迁移旧版数据结构
          const migrated = Object.entries(stored.diaries).reduce((acc, [date, entries]) => {
            entries.forEach(entry => {
              const id = generateId()
              acc.diaries[id] = { ...entry, id, date }
              acc.dateIndex[date] = [...(acc.dateIndex[date] || []), id]
            })
            return acc
          }, { diaries: {}, dateIndex: {} })
        
          diaries.value = migrated.diaries
          dateIndex.value = migrated.dateIndex
        } else if (stored._version === 2) {
          diaries.value = stored.diaries
          dateIndex.value = stored.dateIndex
        }
      
        motto.value = stored.motto || motto.value
        markedDates.value = stored.markedDates || []
        calendarBgImage.value = stored.calendarBgImage || null // 新增：初始化背景图
      }
    } catch (error) {
      console.error('Storage init error:', error)
    }
  }

  // ==================== 核心操作 ====================
  const saveDiary = (content, images = [], diaryId = null) => {
    const id = diaryId || generateId()
    const date = selectedDate.value

    // 更新或新建条目
    const existing = diaries.value[id]
    diaries.value[id] = {
      ...(existing || {}),
      id,
      date,
      content,
      images: images.map(processImagePath),
      createdAt: existing?.createdAt || new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }

    // 维护日期索引
    if (!dateIndex.value[date]) dateIndex.value[date] = []
    if (!dateIndex.value[date].includes(id)) {
      dateIndex.value[date].unshift(id)
    }

    // 更新标记日期
    if (!markedDates.value.includes(date)) {
      markedDates.value.push(date)
      markedDates.value.sort()
    }

    return saveToStorage()
  }

  // 新增：背景图保存方法
  // 修改 saveCalendarBgImage 方法
  const saveCalendarBgImage = async (tempPath) => {
    try {
      if (!tempPath) {
        // 清除背景时的处理
        calendarBgImage.value = null
        await saveToStorage()
        return true
      }
      
      // 原有保存逻辑...
      const savedPath = await new Promise((resolve) => {
        uni.saveFile({
          tempFilePath: tempPath,
          success: (res) => resolve(res.savedFilePath),
          fail: () => resolve(null)
        })
      })
      
      calendarBgImage.value = savedPath ? `_www/${savedPath}` : null
      return saveToStorage()
    } catch (error) {
      console.error('背景图操作失败:', error)
      return false
    }
  }

  const deleteDiary = (diaryId) => {
    if (!diaries.value[diaryId]) return

    const date = diaries.value[diaryId].date
    // 移除日期索引
    dateIndex.value[date] = dateIndex.value[date].filter(id => id !== diaryId)
  
    // 清理空日期
    if (dateIndex.value[date].length === 0) {
      delete dateIndex.value[date]
      markedDates.value = markedDates.value.filter(d => d !== date)
    }

    // 移除条目
    delete diaries.value[diaryId]
    return saveToStorage()
  }

  // ==================== 增强功能 ====================
  const moveDiaryDate = async (diaryId, newDate) => {
    const entry = diaries.value[diaryId]
    if (!entry || entry.date === newDate) return

    // 原日期清理
    dateIndex.value[entry.date] = dateIndex.value[entry.date].filter(id => id !== diaryId)
  
    // 新日期添加
    entry.date = newDate
    if (!dateIndex.value[newDate]) dateIndex.value[newDate] = []
    dateIndex.value[newDate].unshift(diaryId)

    // 更新标记日期
    if (!markedDates.value.includes(newDate)) {
      markedDates.value.push(newDate)
      markedDates.value.sort()
    }

    return saveToStorage()
  }

  // ==================== 持久化优化 ====================
  const saveToStorage = async () => {
    try {
      await setStorage('homeStore', {
        _version: 2,
        motto: motto.value,
        diaries: diaries.value,
        dateIndex: dateIndex.value,
        markedDates: markedDates.value,
        calendarBgImage: calendarBgImage.value // 新增：存储背景图
      })
    } catch (error) {
      console.error('Storage save error:', error)
      throw new Error('存储失败，请检查空间容量')
    }
  }

  // ==================== 计算属性 ====================
  const currentDateDiaries = computed(() => {
    return (dateIndex.value[selectedDate.value] || [])
      .map(id => diaries.value[id])
      .sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
  })

  const allDiaries = computed(() => 
    Object.values(diaries.value).sort((a, b) => 
      new Date(b.updatedAt) - new Date(a.updatedAt)
    )
  )

  return {
    motto,
    selectedDate,
    diaries,
    dateIndex,
    markedDates,
    calendarBgImage, // 新增：导出背景图状态
    currentDateDiaries,
    allDiaries,
  
    initFromStorage,
    updateMotto: (newMotto) => {
      motto.value = newMotto
      saveToStorage()
    },
    setSelectedDate: (date) => {
      selectedDate.value = date
    },
    saveDiary,
    deleteDiary,
    moveDiaryDate,
    saveCalendarBgImage // 新增：导出背景图保存方法
  }
})